//
//  NGForumSingleTableView.swift
//  NingguoForum
//
//  Created by zhengsw on 2025/7/17.
//  Copyright © 2025 zhengsw. All rights reserved.
//

import UIKit
import SnapKit
import ObjectMapper
import ESPullToRefresh

// MARK: - Protocol
protocol NGForumSingleTableViewDelegate: AnyObject {
    func forumSingleTableView(_ tableView: NGForumSingleTableView, didSelectItemAt indexPath: IndexPath)
    func forumSingleTableViewDidTriggerRefresh(_ tableView: NGForumSingleTableView)
    func forumSingleTableViewDidTriggerLoadMore(_ tableView: NGForumSingleTableView)
}

class NGForumSingleTableView: UIView {
    
    // MARK: - Properties
    let tabIndex: Int
    let title: String
    var page: Int = 1
    private var currentPage: Int = 1
    private var dataSource: [ResponseForumDetailListDataModel] = []
    var paramters = NSMutableDictionary()
    
    weak var delegate: NGForumSingleTableViewDelegate?
    
    // MARK: - UI Components
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.tag = tabIndex
        tableView.backgroundColor = .white
        tableView.separatorStyle = .singleLine
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(NGForumTableViewCell.self, forCellReuseIdentifier: "NGForumTableViewCell")
        tableView.showsVerticalScrollIndicator = false
        return tableView
    }()
    
    // MARK: - Initialization
    init(tabIndex: Int, title: String, paramters: NSDictionary) {
        self.tabIndex = tabIndex
        self.title = title
        self.paramters = paramters as! NSMutableDictionary;
        super.init(frame: .zero)
        setupUI()
        
        loadForumData(page: self.page)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        addSubview(tableView)
        
        var footer: ESRefreshFooterAnimator {
            get {
                let f = ESRefreshFooterAnimator.init(frame: CGRect.zero)
                f.loadingMoreDescription = "上拉加载更多"
                f.noMoreDataDescription = "数据已加载完"
                f.loadingDescription = "加载更多..."
                return f
            }
        }

        self.tableView.es.addInfiniteScrolling(animator: footer) { [weak self] in
            guard let self = self else { return }
            self.loadForumData(page: self.page)
        }
        
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    private func loadForumData(page:Int) {
        // 现代用法（推荐）
        HttpManager.sharedInstance.fetchForumList(
            page: page,
            step: 10,
            circleId: paramters["circleId"] as! String,
            fid: paramters["fid"] as! String
        ) { [weak self] result in
            DispatchQueue.main.async {
                guard let self = self else { return }
                switch result {
                case .success(let data):

                    self.tableView.es.stopLoadingMore()
                    let list = data.list ?? []
                    if (list.count == 0 && self.page != 1) {
                        return
                    }
                    if (self.page == 1) {
                        self.updateUI(with: list)
                    } else {
                        self.appendDataSource(list)
                    }

                    self.page += 1
                    if self.dataSource.count == 0 {
                        self.tableView.es.noticeNoMoreData()
                        return
                    }
                case .failure(let error):
                    self.handleError(error)
                }
            }
        }
    }
    
    private func updateUI(with list: [ResponseForumDetailListDataModel]) {
        // 更新UI
        print("加载到 \(list.count) 条数据")
        self.updateDataSource(list)
    }
        
    private func handleError(_ error: Error) {
        if let networkError = error as? NetworkError {
            // 显示具体的错误信息
            showAlert(title: "错误", message: networkError.localizedDescription)
        } else {
            // 显示通用错误信息
            showAlert(title: "错误", message: error.localizedDescription)
        }
        
    }
        
    private func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        //            present(alert, animated: true)
        
    }

    // MARK: - Public Methods
    func reloadData() {
        tableView.reloadData()
    }
    
    func endRefreshing() {
        tableView.refreshControl?.endRefreshing()
    }
    
    func endLoadMore() {
        // 结束上拉加载更多
        // 如果使用 MJRefresh，这里调用相应的结束方法
    }
    
    func updateDataSource(_ data: [ResponseForumDetailListDataModel]) {
        self.dataSource = data
        tableView.reloadData()
    }
    
    func appendDataSource(_ data: [ResponseForumDetailListDataModel]) {
        self.dataSource.append(contentsOf: data)
        tableView.reloadData()
    }
}

// MARK: - UITableViewDataSource
extension NGForumSingleTableView: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NGForumTableViewCell", for: indexPath) as! NGForumTableViewCell
        
        let model = dataSource[indexPath.row]
        cell.configure(with: model)
        
        return cell
    }
}

// MARK: - UITableViewDelegate
extension NGForumSingleTableView: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        delegate?.forumSingleTableView(self, didSelectItemAt: indexPath)
    }
}
